import { useState, useRef, useEffect } from 'react';
import { useBoolean } from 'ahooks';
import { Space, Button, App, Modal, Tree, Dropdown, Typography } from 'antd';
import type { TreeDataNode } from 'antd';
import { getRoleList, DeleteRole, getMenuTree, UpdateRoleToMenus } from 'src/api/modules/system';
import Table from 'src/components/Table';
import PermissionButton from 'src/components/Permission';
import { IRoleRespData, IMenuRespData } from 'src/interface';
import { schemas, columns } from './data';
import RoleModal from './RoleModal';

enum TreeHandleEnum {
  SelectAll,
  UnSelectAll,
  Expand,
  Collapse,
}

const Link = Typography.Link;

export default function RoleManage() {
  const [visible, { setTrue, setFalse }] = useBoolean(false);
  const [visibleMenu, { setTrue: setMenuTrue, setFalse: setMenuFalse }] = useBoolean(false);
  const [saveLoading, { setTrue: setSaveLoadingTrue, setFalse: setSaveLoadingFalse }] =
    useBoolean(false);

  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [data, setData] = useState<IRoleRespData | null>(null);
  const [menuTree, setMenuTree] = useState<TreeDataNode[]>([]);
  const tableRef = useRef<{ onRefresh: () => void; data: any[] }>({
    onRefresh: () => {},
    data: [],
  });
  const [roleId, setRoleId] = useState<string>();
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const expandedKeyRef = useRef<string[]>([]);

  const { modal, message } = App.useApp();

  const setVisibleHandle = (data?: IRoleRespData) => {
    setTrue();
    setData(data ? data : null);
  };

  const onDelete = async (ids: string[]) => {
    modal.confirm({
      title: '删除角色',
      content: '确定删除角色吗？',
      onOk: async () => {
        try {
          await DeleteRole(ids);
          tableRef.current.onRefresh();
        } catch (err) {
          console.log(err);
        }
      },
    });
  };
  // 打开编辑菜单弹框
  const visibleEditMenu = (id: string, sysRoleMenus: { roleId: string; menuId: string }[]) => {
    setRoleId(id);
    setMenuTrue();
    setCheckedKeys(sysRoleMenus.map((item) => item.menuId));
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  // 获取菜单树列表
  const getMenuTreeData = async () => {
    setSaveLoadingTrue();
    try {
      const data = await getMenuTree();
      const expandedkey = [] as string[];
      const transformData = (data: IMenuRespData): TreeDataNode => {
        if (data.children?.length) {
          expandedkey.push(data.menuId);
        }
        return {
          title: data.name ?? '',
          key: data.menuId,
          children: data.children?.map(transformData),
        };
      };
      const result = data ? data.map(transformData) : [];
      setMenuTree(result);
      expandedKeyRef.current = expandedkey;
      setExpandedKeys(expandedkey);
    } catch (err) {
      console.log(err);
    } finally {
      setSaveLoadingFalse();
    }
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    setCheckedKeys(checkedKeysValue);
  };

  const onTreeHandle = (key: TreeHandleEnum) => {
    switch (key) {
      case TreeHandleEnum.SelectAll:
        setCheckedKeys(menuTree.map((item) => item.key));
        break;
      case TreeHandleEnum.UnSelectAll:
        setCheckedKeys([]);
        break;
      case TreeHandleEnum.Expand:
        setExpandedKeys(expandedKeyRef.current);
        break;
      case TreeHandleEnum.Collapse:
        setExpandedKeys([]);
    }
  };

  const saveMenuTree = async () => {
    if (!roleId) return;
    try {
      const data = {
        roleId,
        menuIds: checkedKeys as string[],
      };
      await UpdateRoleToMenus(data);
      setMenuFalse();
      message.success('保存成功，刷新后权限生效');
    } catch (err) {
      console.log(err);
    }
    //  tableRef.current.onRefresh();
  };

  useEffect(() => {
    getMenuTreeData();
  }, []);

  return (
    <div className="m-[16px] rounded-md min-[calc(100vh - 32px)]">
      <Table
        ref={tableRef}
        downloadName="角色管理"
        formProps={{ schemas }}
        rowSelection={{
          selectedRowKeys,
          onChange: onSelectChange,
        }}
        columns={[
          ...columns,
          {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            width: 150,
            render: (_text: string, record: IRoleRespData) => {
              return (
                <Space size={'small'}>
                  <Link onClick={() => setVisibleHandle(record)}>编辑</Link>
                  <Link onClick={() => visibleEditMenu(record.roleId, record.sysRoleMenus)}>
                    编辑菜单
                  </Link>
                  <PermissionButton
                    permission="SYSTEM_ROLE_DELETE"
                    type="link"
                    onClick={() => onDelete([record.roleId])}>
                    删除
                  </PermissionButton>
                </Space>
              );
            },
          },
        ]}
        rowKey="roleId"
        request={getRoleList}
        left={
          <Button type="primary" onClick={() => setVisibleHandle()}>
            新增角色
          </Button>
        }
        right={
          <PermissionButton
            permission="SYSTEM_ROLE_DELETE"
            disabled={!selectedRowKeys.length}
            danger
            onClick={() => onDelete(selectedRowKeys as string[])}>
            批量删除
          </PermissionButton>
        }></Table>
      <RoleModal
        onOk={() => tableRef.current.onRefresh()}
        maskClosable={false}
        data={data}
        open={visible}
        onCancel={setFalse}></RoleModal>
      <Modal
        title="配置菜单权限"
        open={visibleMenu}
        onCancel={setMenuFalse}
        maskClosable={false}
        width={400}
        footer={null}
        classNames={{ body: 'max-h-[600px] overflow-y-auto overflow-x-hidden' }}>
        <Tree
          checkable
          blockNode
          defaultExpandAll
          checkStrictly
          onCheck={(value) => onCheck((value as { checked: React.Key[] }).checked)}
          checkedKeys={checkedKeys}
          expandedKeys={expandedKeys}
          treeData={menuTree}
        />
        <div className="flex justify-between items-center mt-[40px]">
          <Dropdown
            trigger={['click']}
            menu={{
              items: [
                { key: TreeHandleEnum.SelectAll, label: '全选' },
                { key: TreeHandleEnum.UnSelectAll, label: '取消全选' },
                { key: TreeHandleEnum.Expand, label: '展开' },
                { key: TreeHandleEnum.Collapse, label: '折叠' },
              ],
              onClick: ({ key }) => onTreeHandle(Number(key) as TreeHandleEnum),
            }}
            placement="bottom">
            <Button>更多操作</Button>
          </Dropdown>
          <div className="flex">
            <Space>
              <Button onClick={setMenuFalse}>取消</Button>
              <PermissionButton
                permission="SYSTEM_ROLE_MENU"
                type="primary"
                onClick={saveMenuTree}
                loading={saveLoading}>
                保存
              </PermissionButton>
            </Space>
          </div>
        </div>
      </Modal>
    </div>
  );
}
